package com.wly.ui
{
	import com.wly.ActiveManager;
	import com.wly.datapool.define.GlobalDefine;
	import com.wly.datapool.global.GlobalInfo;
	import com.wly.datapool.map.MapInfo;
	import com.wly.datapool.tower.TowerInfo;
	import com.wly.datapool.tower.TowerPool;
	import com.wly.ui.common.ItemCell;
	import com.wly.utils.Func;
	import com.wly.utils.MyPoint;
	
	import flash.display.MovieClip;
	
	public class BGLayer extends MovieClip
	{
		private var _bg:MovieClip;
		private var _itemCells:Array;
		
		private var _widthNum:int;
		private var _heightNum:int;
		private var _vaildCells:Array = [];
		static private var _instance:BGLayer;
		
		public function BGLayer()
		{
			super();
			_instance = this;
			init();
		}
		
		static public function getInstance():BGLayer
		{
			return _instance;
		}
		
		private function init():void
		{
			var i:int;
			var j:int;
			var itemCell:ItemCell;
			
			_widthNum  = (GlobalDefine.MAP_WIDTH-1)/GlobalDefine.CELL_WIDTH+1;
			_heightNum = (GlobalDefine.MAP_HEIGHT-1)/GlobalDefine.CELL_HEIGHT+1;
			_itemCells = [];
			for(i=0; i<_heightNum; i++)
			{
				for(j=0; j<_widthNum; j++)
				{
					itemCell   = new ItemCell;
					itemCell.x = j*GlobalDefine.CELL_WIDTH;
					itemCell.y = i*GlobalDefine.CELL_HEIGHT;
					itemCell.index = _widthNum*i+j;
					addChild(itemCell);
					_itemCells.push(itemCell);
				}
			}
		}
		
		public function reset():void
		{
			if(_bg)
			{
				removeChild(_bg);
			}
			removeCellEvents();
		}
		
		public function updateMap(mapInfo:MapInfo):void
		{
			var i:int;
			var len:int;
			var itemCell:ItemCell;
			
			removeCellEvents();
			if(_bg)
			{
				removeChild(_bg);
			}
			if(mapInfo)
			{
				_bg = mapInfo.mapImg;
				_bg.mouseEnabled = false;
				addChildAt(_bg, 0);
				
				_vaildCells = mapInfo.towerPostions;
				setCellEvents();
			}
		}
		
		private function removeCellEvents():void
		{
			var i:int;
			var len:int;
			var itemCell:ItemCell;
			
			len = _vaildCells.length;
			for(i=0; i<len; i++)
			{
				itemCell = _itemCells[i] as ItemCell;
				itemCell.clickUI = null;
			}
		}
		
		private function setCellEvents():void
		{
			var i:int;
			var len:int;
			var itemCell:ItemCell;
			var val:int;
			
			len = _vaildCells.length;
			for(i=0; i<len; i++)
			{
				val = _vaildCells[i] as int;
				itemCell = _itemCells[val] as ItemCell;
				itemCell.clickUI = this;
			}
		}
		
		public function onItemClick(index:int):void
		{
			var itemCell:ItemCell = _itemCells[index] as ItemCell;
			var pos:MyPoint = Func.caculateCellPos(index);
			var tower:TowerInfo =  TowerPool.getInstance().createTower(GlobalInfo.selectTowerIndex);
			if(tower)
			{
				tower.model.x        = pos.x
				tower.model.y        = pos.y;
				ActiveManager.getInstance().addTower(tower);
				itemCell.tower = tower;
			}
		}
	}
}